<?php

namespace App\Http\Resources\Index\Summary;

use App\Http\Resources\Resource;
use App\Http\Resources\Traits\Attributes;
use Helper\Timed;

class DataResource extends Resource
{
    use Attributes;

	public static $isEs = false;
    /**
     * Transform the resource into an array.
     *
     * @param \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        $amounts = array_column($this->resource->toArray(), 'amount', 'timed');

	    date_default_timezone_set(Timed::getTimezoneName());

		if (Timed::getTimezoneName() == 'America/Scoresbysund') {

			if ($amounts) {
				if (self::$isEs) {
					foreach ($amounts as $k => $v) {
						$charts['timed'][] = date('Y.m.d', $k);
						$charts['data'][]  = $v;
					}
				} else {
					$timedEnd = Timed::getTodayTimed();
					$timed = $timedEnd - 86400 * 6;

					for (; $timed <= $timedEnd; $timed += 86400) {
						$charts['timed'][] = date('Y.m.d', $timed);
						$charts['data'][] = $amounts[$timed] ?? 0;
					}
				}
			} else {
				$timedEnd = Timed::getTodayTimed();
				$timed = $timedEnd - 86400 * 6;

				for (; $timed <= $timedEnd; $timed += 86400) {
					$charts['timed'][] = date('Y.m.d', $timed);
					$charts['data'][] =  0;
				}
			}
		} else {
			$timedEnd = Timed::getTodayTimed();
			$timed = $timedEnd - 86400 * 6;

			for (; $timed <= $timedEnd; $timed += 86400) {
				$charts['timed'][] = date('Y.m.d', $timed);
				$charts['data'][] = $amounts[$timed] ?? 0;
			}
		}


        $this->setAttribute('chart', $charts);

        return $this->getResponse()->setResponseData($this->getAttributes());
    }
}
